<template>
  <div id="app">
    <a @click="goback()">
      <h1  style="color: white">《《《返回首页</h1>
    </a>
    <lemon-imui :user='this.user' ref='IMUI' @menu-avatar-click="handleMenuAvatarClick"
      @pull-messages='handlePullMessages' @send="handleSend" @change-contact="handleChangeContact"
      style="position: relative;left: 20%"></lemon-imui>
  </div>
</template>
<script>
import axios from 'axios';
import '../../api/request';
// import io from "socket.io-client"
let lockReconnect;
let rec;
export default {
  data() {
    return {
      aWebSocket: null,
      IMUI: null,
      user: {
        id: JSON.parse(localStorage.getItem("user")).id,
        displayName: JSON.parse(localStorage.getItem("user")).nickname,
        avatar: JSON.parse(localStorage.getItem("user")).avatar,
      },
    }
  },
  mounted() {
    this.IMUI = this.$refs.IMUI,
      // this.socket = io("http://127.0.0.1:8089")

      //初始化表情包。
      // IMUI.initEmoji(...);
      //从后端请求联系人数据，包装成下面的样子
      
    this.initContact();
    this.aWebSocket = new WebSocket('ws://localhost:8088/ws/' + this.user.id);

    this.aWebSocket.onpen = function (event) {
      lockReconnect = true;
      console.log("-------------------onpen:" + event)
    }

    var that = this
    this.aWebSocket.onmessage = function (event) {
      //将接收到的数据包装成下面的样子
      console.log(event.data);
      var temp
      if (event.data === 'PING') {

      } else {
        temp = JSON.parse(event.data);
      }

      console.log(temp);
      var data;
      if (temp) {
        data = {
          id: temp.id,
          status: temp.status,
          type: temp.type,
          sendTime: temp.sendTime,
          content: temp.content,
          toContactId: temp.hostId,
          fromUser: {
            //如果 id == this.user.id消息会显示在右侧，否则在左侧
            id: temp.hostId,
            displayName: temp.displayName,
            avatar: temp.avatar,
          }
        }
        that.IMUI.appendMessage(data);
        this.IMUI.messageViewToBottom();
      }
      console.log("------------------------------data")
      console.log(data)

    };

    this.aWebSocket.close = function (event) {
      lockReconnect = false;
      console.log('链接关闭' + event.code + new Date().getTime());
      // 服务器关闭  不重连
      if (event.code != 1006) {
        that.reconnect();
      }
    }

    this.aWebSocket.onerror = function (event) {
      lockReconnect = false;
      that.reconnect();
      console.log("---------------------error:" + event)
    }

    window.onbeforeunload = this.aWebSocket.close();

  },





  methods: {
    goback() {
      window.location.href = "index.html"
    },
    //初始化联系人
    initContact() {
      axios.get("/contact/list").then(res => {
        var contactList = []
        var content = res.data.data

        if (res.data.code === 1) {
          content.forEach(e => {
            const contacts = [{
              id: e.id,
              displayName: e.displayName,
              avatar: e.avatar,
              index: e.sort,
              unread: e.unread,
              //最近一条消息的内容，如果值为空，不会出现在“聊天”列表里面。
              //lastContentRender 函数会将 file 消息转换为 '[文件]', image 消息转换为 '[图片]'，对 text 会将文字里的表情标识替换为img标签,
              lastContent: this.IMUI.lastContentRender({ type: 'text', content: e.lastContent }),
              //最近一条消息的发送时间
              lastSendTime: e.lastSendTime,
            }];
            contactList.push(...contacts)
          });
        }
        this.IMUI.initContacts(contactList);
      })

    },
    //拉取消息列表
    handlePullMessages(contact, next) {
      //从后端请求消息数据，包装成下面的样子

      axios.get(`/messages/list/${contact.id}`).then(res => {

        var messages = res.data.data;

        if (res.data.code === 1) {
          messages.forEach(e => {
            const user = {
              id: e.hostId,
              displayName: e.displayName,
              avatar: e.avatar,
            }
            const message = [{
              id: e.id,
              status: 'succeed',
              type: 'text',
              sendTime: e.sendTime,
              content: e.content,
              toContactId: this.user.id,
              fromUser: user,
            }]
            console.log(message)
            next(message, true)
          });

        }
        if (res.data.code === 0) {
          const messages = [{
            id: '1',
            status: 'succeed',
            type: 'text',
            sendTime: 1566047865417,
            content: '',
            toContactId: this.user.id,
            fromUser: this.user
          }]
          //将第二个参数设为true，表示已到末尾，聊天窗口顶部会显示“暂无更多消息”，不然会一直转圈。
          next(messages, true);
        }

      })

      //将第二个参数设为true，表示已到末尾，聊天窗口顶部会显示“暂无更多消息”，不然会一直转圈。
      // next(messagesList, true);
    },
    //发送消息
    handleSend(message, next, file) {
      var temp = {
        // id: message.id,
        status: message.status,
        type: message.type,
        sendTime: message.sendTime,
        content: message.content,
        toContactId: message.toContactId,
        hostId: this.user.id,
        displayName: this.user.displayName,
        avatar: this.user.avatar
      }
      // this.socket.emit("talk", temp)
      axios.put('/messages/save', temp).then(res => {
        this.aWebSocket.send(JSON.stringify(temp));
      })
      setTimeout(() => {
        next();
      }, 1000);
      //执行到next消息会停止转圈，如果接口调用失败，可以修改消息的状态 next({status:'failed'});
      next();
    },

    //点击头像事件
    handleMenuAvatarClick() {
      window.location.href = "personalCenter.html"
    },

    //点击聊天窗口中的消息时会触发该事件
    handleMessageClick(e, key, message, instance) {
      console.log("点击了消息", e, key, message);

      if (key == "status") {
        instance.updateMessage({
          id: message.id,
          status: "going",
          content: "正在重新发送消息...",
        });
        setTimeout(() => {
          instance.updateMessage({
            id: message.id,
            status: "succeed",

          });
          alert("发送成功")
        }, 1000);
      }
    },

    //	点击聊天窗口中的消息时会触发该事件
    handleChangeContact(contact, instance) {
      console.log("Event:change-contact");
      instance.updateContact({
        id: contact.id,
        unread: 0,
      });
      instance.closeDrawer();
    }, 

    reconnect() {
      if (lockReconnect) {
        return;
      };
      //没连接上会一直重连，设置延迟避免请求过多，  有定时任务 先取消再设置
      rec && clearTimeout(rec);
      rec = setTimeout(function () {
        createWebSocket();
      }, 2000);
    }

  }
}

</script>

<style lang="stylus">
  ::selection{background:#000;color:#fff;}
  body
    font-family "Microsoft YaHei"
    background: url(http://rww08uahf.hn-bkt.clouddn.com/0dd8ed5b730c4df7babec5898c4b641c.png);

  #app
    width 90%
    margin 0 auto
    padding-bottom 100px
    .scroll-top
      cursor pointer
      position fixed
      bottom 40px
      left 50%
      border-radius 50%
      background #fff
      font-size 18px
      overflow hidden
      width 40px
      height 40px
      line-height 40px
      user-select none
      text-align center
      transform rotate(-45deg) translateX(-50%)
      box-shadow 0 0 30px rgba(0,0,0,0.1);
      &:hover
        font-size 22px
  a
    color #0c5ed9
    text-decoration none
    font-size 12px
  .action
    margin-top 20px
    .lemon-button
      margin-right 10px
      margin-bottom 10px
  .link
    font-size 14px
    margin-top 15px
    a
      display inline-block
      margin 0 5px
      text-decoration none
      background #ffba00
      border-radius 4px
      padding 5px 10px
      color rgba(0,0,0,0.8)
  .logo
    position relative
    display inline-block
    margin 60px auto
    user-select none
  .logo-text
    font-size 38px
  .logo-sub
    font-size 18px
    color #999
    font-weight 300
  .logo-badge
    position absolute
    top -10px
    left 230px
    background #000
    border-radius 16px
    color #f9f9f9
    font-size 12px
    padding 4px 8px
  .title
    font-size 24px
    line-height 26px
    border-left 1px solid #ffba00
    padding-left 15px
    margin-bottom 15px
    margin-top 30px
    user-select none
  .table
    width 100%
    border-radius 10px
    background #fff
    border-collapse collapse
    tr
      cursor pointer
    tr:not(.table-head):hover
      background #ffba00 !important
    tr:nth-of-type(even)
      background #f9f9f9
    th
      user-select none
      color #999
    td,
    th
      text-align left
      padding 10px 15px
      font-size 14px
      font-weight normal
  .imui-center
    margin-bottom 60px
    .lemon-wrapper
      border:1px solid #ddd;
    .lemon-drawer
      border:1px solid #ddd;
      border-left:0;
  .drawer-content
    padding 15px
  .more
    font-size 12px
    line-height 24px
    height 24px
    position absolute
    top 14px
    right 14px
    cursor pointer
    user-select none
    color #f1f1f1
    display inline-block
    border-radius 4px
    background #111
    padding 0 8px
    &:active
      background #999
  .bar
    text-align center
    line-height 30px
    background #fff
    margin 15px
    color #666
    user-select none
    font-size 12px
  .cover
    text-align center
    user-select none
    position absolute
    top 50%
    left 50%
    transform translate(-50%,-50%)
    i
      font-size 84px
      color #e6e6e6
    p
      font-size 18px
      color #ddd
      line-height 50px
  .article-item
    line-height 34px
    cursor pointer
    &:hover
      text-decoration underline
      color #318efd
  pre
    background #fff
    border-radius 8px
    padding 15px
  .lemon-simple .lemon-container{
    z-index:5
  }
  .lemon-simple .lemon-drawer{
    z-index:4
  }



  input#switch[type=checkbox]{
      height: 0;
      width: 0;
      display:none;
  }

  label#switch-label {
      cursor: pointer;
      text-indent: -9999px;
      width: 34px;
      height: 20px;
      background: #aaa;
      display: block;
      border-radius: 100px;
      position: relative;
  }

  label#switch-label:after {
      content: '';
      position: absolute;
      top: 2px;
      left: 2px;
      width: 16px;
      height: 16px;
      background: #fff;
      border-radius: 20px;
      transition: 0.3s;
  }

  input#switch:checked + label {
      background: #0fd547;
  }

  input#switch:checked + label:after {
      left: calc(100% - 2px);
      transform: translateX(-100%);
  }

  label#switch-label:active:after {
      width: 20px;
  }
  </style>
